#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <cerrno>
#include <cstring>

const std::string comm_name = "./myfifo";

int main()
{
    //服务端创建命名管道
    int res = mkfifo(comm_name.c_str(),0666);
    if(res != 0)//创建失败
    {
        perror("mkfifo");
    }

    //serve端打开管道
    int fd = open(comm_name.c_str(),O_RDONLY);
    if(fd < 0)
    {
        std::cout<<"open file"<<errno<<std::endl;
    }

    //serve接受消息并打印
    char buffer[1024];
    while(true)
    {
        std::cout<<"server begin read:"<<std::endl;
        ssize_t n = read(fd,buffer,sizeof(buffer)-1);
        if(n > 0)//读取成功
        {
            buffer[n] = 0;
            std::cout<<buffer<<std::endl;
        }
        else if( n == 0)
        {
            std::cout<<"read done"<<std::endl;
            break;
        }
        else
        {
            std::cout<<"read fail"<<errno<<std::endl;
            break;
        }
    }
    int n = unlink(comm_name.c_str());
    if(n != 0)
    {
        perror("unlink");
    }
    return 0;
}